<template>
  <el-card style="height: 100%">
    <!-- 1.面包屑 -->
    <MyBread
      url="administrator"
      level1="系统管理"
      level2="控制面板"
      level3="学员管理"
    />
    <!-- 2.搜索 -->
    <el-input
      placeholder="请输入学员姓名"
      v-model="search"
      class="with-input"
      clearable
    >
      <el-button
        slot="append"
        icon="el-icon-search"
        @click="searchUser"
      ></el-button>
    </el-input>
    <!-- 添加学员按钮 -->
    <el-button type="success" plain @click="dialogVisible">添加学员</el-button>
    <!-- 3.表格 -->
    <el-table :data="UserData" style="width: 100%" stripe>
      <el-table-column prop="id" label="ID" width="50"></el-table-column>
      <el-table-column prop="name" label="姓名" width="100"></el-table-column>
      <el-table-column prop="sex" label="性别" width="100"></el-table-column>
      <el-table-column
        prop="identify"
        label="身份证号"
        width="230"
      ></el-table-column>
      <el-table-column prop="phone" label="联系电话" width="170"></el-table-column>
      <el-table-column
        prop="address"
        label="当前住址"
        width="280"
      ></el-table-column>
      <el-table-column
        prop="model"
        label="申请车型"
        width="100"
      ></el-table-column>
      <el-table-column prop="coach" label="教练" width="100"></el-table-column>
      <el-table-column
        prop="date"
        label="领证日期"
        width="150"
      ></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            circle
            @click="hendleEdit(scope.$index, scope.row)"
            style="margin-right: 10px"
          ></el-button>
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="确定删除该用户信息吗？"
            @confirm="handleDelete(scope.$index, scope.row)"
          >
            <el-button
              slot="reference"
              type="danger"
              circle
              icon="el-icon-delete"
            >
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 4.分页 -->
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[2, 4, 6, 8]"
      :page-size="limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="length"
    >
    </el-pagination>
    <!-- 添加/修改学员的对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogStudentFormVisible"
      width="440"
    >
      <el-form :model="form" :rules="rules" ref="formStudent">
        <el-form-item prop="name">
          <el-input
            v-model="form.name"
            placeholder="姓名"
            :disabled="!isAdd"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-radio-group v-model="form.sex" :disabled="!isAdd">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="identify">
          <el-input
            v-model="form.identify"
            placeholder="身份证号"
            :disabled="!isAdd"
          ></el-input>
        </el-form-item>
        <el-form-item prop="address">
          <el-input v-model="form.address" placeholder="当前住址"></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input v-model.number="form.phone" placeholder="联系电话"></el-input>
        </el-form-item>
        <el-form-item prop="model">
          <el-select
            v-model="form.model"
            placeholder="申请车型"
            style="width: 100%"
            :disabled="!isAdd"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            v-model.lazy="form.date"
            placeholder="选择领证日期"
            style="width: 100%"
            :disabled="datedisable"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="coach">
          <el-select
            v-model="form.coach"
            placeholder="请选择教练"
            style="width: 100%"
            :disabled="!isAdd"
          >
            <el-option
              v-for="item in coachName"
              :key="item.identify"
              :label="item.name"
              :value="item.identify"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCalcel()">取 消</el-button>
        <el-button type="primary" @click="handleUser()">保存信息</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
export default {
  name: "StudentUser",
  data() {
    return {
      search: "", // 搜索输入框输入的内容
      page: 1, // 当前页数
      limit: 2, // 每条页面条数
      length: 0, // 获取数据的长度
      isAdd: true, // false: 编辑 true: 添加
      datedisable: true, // 只有当管理员编辑学员信息时，date-picker生效
      dialogStudentFormVisible: false, // 控制学员对话框的显示与隐藏
      UserData: [], // 请求获取的学员或教练数据
      coachName: [], // 获取教练名集合
      // 学员表单
      form: {
        name: "",
        sex: "男",
        identify: "",
        address: "",
        phone: "",
        model: "",
        date: "",
        coach: "",
      },
      // 学员表单验证规则
      rules: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
          { min: 2, max: 6, message: "长度在2到6个字符", trigger: "blur" },
        ],
        identify: [{ validator: this.validateIdentify, trigger: ["blur", "change"] }],
        address: [{ required: true, message: "住址不能为空", trigger: "blur" }],
        phone: [{ validator: this.checkPhone, trigger: ["blur", "change"] }],
        model: [
          {
            required: true,
            message: "申请车型不能为空",
            trigger: ["blur", "change"],
          },
        ],
        coach: [
          {
            required: true,
            message: "教练名不能为空",
            trigger: ["blur", "change"],
          },
        ],
      },
      title: "",
    };
  },
  methods: {
    // 隐藏对话框 -- 重新获取数据
    dialogCalcel() {
      this.dialogStudentFormVisible = false;
      if (!this.isAdd) {
        this.getStudentListData();
        this.getStudentListDataLength();
      } else {
        this.form = { sex: "男", date: "" };
      }
    },
    // 获取列表数据总长度
    getStudentListDataLength() {
      this.$https
        .getUserData({ url: "/student", like: this.search })
        .then((res) => {
          this.length = res.data.length;
        });
    },
    // 搜索功能实现
    searchUser() {
      this.getStudentListDataLength();
      this.limit = 2;
      this.page = 1;
      this.getStudentListData();
      this.search = "";
    },
    // 获取学员数据
    getStudentListData() {
      this.$https
        .getUserData({
          url: "/student",
          page: this.page,
          limit: this.limit,
          like: this.search,
        })
        .then((res) => {
          this.UserData = res.data;
        });
    },
    // 当每页条数发生变化使调用
    handleSizeChange(val) {
      this.limit = val;
      this.page = 1;
      this.getStudentListData();
    },
    // 当页数发生变化时调用
    handleCurrentChange(val) {
      this.page = val;
      this.getStudentListData();
    },
    // 显示添加学员的对话框（添加学员权限）
    async dialogVisible() {
      if (!(await this.haveThisPermission(this.$route.path, "添加学员"))) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      // 清空表单
      this.form = { sex: "男", date: "" };
      this.datedisable = true;
      // 显示添加学员对话框
      this.isAdd = true;
      this.title = "添加学员信息";
      this.dialogStudentFormVisible = true;
    },
    // 添加学员信息到json-server数据库
    addUser() {
      this.$refs["formStudent"].validate(async (valid) => {
        if (valid) {
          this.dialogStudentFormVisible = false;
          // 关于教练信息的处理、关于教练id的处理
          this.coachName.forEach((element) => {
            if (element.identify === this.form.coach) {
              this.form.coach = element.name;
              this.form.coachID = element.id;
            }
          });
          // 添加学员信息
          await this.$https.addUserData("/student", this.form);
          // 封装相应账号 -- 形成默认账号
          const date = new Date();
          let account = {
            username: this.form.identify,
            password:
              "j" + this.form.identify.substring(this.form.identify.length - 6),
            rolename: "student",
            createTime:
              date.getFullYear() +
              "-" +
              (date.getMonth() + 1) +
              "-" +
              date.getDate(),
          };
          // 添加账号
          await this.$https.addUserData("/login", account);
          // 重新获取学员数据
          this.page = 1;
          this.search = "";
          this.getStudentListData();
          // 重新获取学员长度
          this.getStudentListDataLength();
          // 清空表单
          this.form = { sex: "男", date: "" };
          // 提示信息
          this.$message.success("学员添加成功");
        } else {
          this.$message.info("表单验证信息不通过");
        }
      });
    },
    // 根据id更新学员信息到json-server数据库
    updateUser() {
      this.$refs["formStudent"].validate((valid) => {
        if (valid) {
          this.dialogStudentFormVisible = false;
          // 发送数据
          this.$https
            .updateUserData("/student", this.form.id, this.form)
            .then(() => {
              // 重新获取学员数据
              this.page = 1;
              this.search = "";
              this.getStudentListData();
              this.getStudentListDataLength();
              // 清空表单
              this.form = { sex: "男", date: "" };
              // 提示信息
              this.$message.success("学员修改成功");
            });
        } else {
          this.$message.warning("表单验证信息不通过");
        }
      });
    },
    // 删除学员（删除学院权限）
    async handleDelete(_, row) {
      if (!(await this.haveThisPermission(this.$route.path, "删除学员"))) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      await this.$https.deleteUserData("/student", row.id);
      const { data } = await this.$https.getUser({ like: row.identify });
      // 删除对应账号
      await this.$https.deleteUserData("/login", data[0].id);
      // 重新获取学员数据
      this.page = 1;
      this.search = "";
      this.getStudentListData();
      this.getStudentListDataLength();
      // 提示信息
      this.$message.success("学员删除成功");
    },
    // 获取所有教练名
    getCoachName() {
      this.$https.getUserData({ url: "/coach" }).then((res) => {
        res.data.forEach((element) => {
          this.coachName.push({
            id: element.id,
            identify: element.identify,
            name: element.name,
          });
        });
      });
    },
    // 确定是添加还是编辑操作
    handleUser() {
      if (this.isAdd) {
        this.addUser();
      } else {
        this.updateUser();
      }
    },
    // 编辑学员信息（修改学员权限）
    async hendleEdit(_, row) {
      if (!(await this.haveThisPermission(this.$route.path, "修改学员"))) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      this.isAdd = false;
      this.title = "编辑学员信息";
      this.form = row;
      this.dialogStudentFormVisible = true;
      // date-picker的使能
      this.datedisable = false;
    },
  },
  async mounted() {
    this.getStudentListDataLength();
    this.getCoachName();
    this.getStudentListData();
  },
};
</script>

<style scoped>
.with-input {
  width: 500px;
  margin-top: 30px;
  margin-bottom: 30px;
  margin-right: 10px;
}
.pagination {
  margin-top: 30px;
}
</style>